﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using IZ.WebFileManager;
using System.IO;

namespace IFTRUE.FMS.Web.Aspx
{
    public partial class FileManage : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (!string.IsNullOrEmpty(MySession.CurrentUser.Folder))
                {
                    FileManager1.RootDirectories[0].DirectoryPath = MySession.CurrentUser.Folder;
                    lblMsg.Text = "当前路径：" + ((MySession.CurrentUser.Folder.IndexOf("~") == 0) ? Server.MapPath(MySession.CurrentUser.Folder) : MySession.CurrentUser.Folder);
                }
            }
        }

        protected void FileManager1_ExecuteCommand(object sender, ExecuteCommandEventArgs e)
        {
            if (Page.IsCallback)
            {
            }
            else
            {
                if (e.CommandName == "EditText")
                {
                    if (e.Items.Count == 0)
                        return;

                    FileManagerItemInfo item = e.Items[0];
                    ViewState["EditDocumentPath"] = item.PhysicalPath;
                    string text = File.ReadAllText(item.PhysicalPath);

                    txtContent.Text = text;

                    FileManager1.Visible = false;
                    TextEditor.Visible = true;
                }
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            string filePath = (string)ViewState["EditDocumentPath"];
            File.WriteAllText(filePath, txtContent.Text);

            FileManager1.Visible = true;
            TextEditor.Visible = false;
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            FileManager1.Visible = true;
            TextEditor.Visible = false;
        }

        protected void FileManager1_FileDeleting(object sender, DeleteItemsActionEventArgs e)
        {
            if(string.IsNullOrEmpty(FileManager1.RecyclePath))
            {
                return;
            }
            //在文件删除前将文件备份到回收站
            if (e.SelectedItems != null && e.SelectedItems.Count > 0)
            {
                string strNewFile = (FileManager1.RecyclePath.IndexOf("~")==0)?Server.MapPath(FileManager1.RecyclePath):FileManager1.RecyclePath;
                if (strNewFile.LastIndexOf("\\") != 0)
                    strNewFile+="\\";
                foreach (FileInfo file in e.SelectedItems)
                {
                    new BLL.Log().Add(2, "文件管理", string.Format("用户（{0}）删除文件{1}", MySession.CurrentUser.Account, file.FullName));
                    if (file.Exists)
                    {
                        File.Copy(file.FullName, strNewFile + DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + file.Name,false);
                    }
                    else if(file.Directory.Exists)
                    {
                      CopyDir(file.FullName, strNewFile + DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + file.Name);
                    }
                }
            }
        }

        /// <summary>
        /// 复制文件夹或文件
        /// </summary>
        /// <param name="srcPath">源文件夹(文件)路径</param>
        /// <param name="decPath">目标文件夹路径</param>
        public static void CopyDir(string fromDir, string toDir)
        {
            if (!Directory.Exists(fromDir))
                return;

            if (!Directory.Exists(toDir))
            {
                Directory.CreateDirectory(toDir);
            }

            string[] files = Directory.GetFiles(fromDir);
            foreach (string formFileName in files)
            {
                string fileName = Path.GetFileName(formFileName);
                string toFileName = Path.Combine(toDir, fileName);
                File.Copy(formFileName, toFileName);
            }
            string[] fromDirs = Directory.GetDirectories(fromDir);
            foreach (string fromDirName in fromDirs)
            {
                string dirName = Path.GetFileName(fromDirName);
                string toDirName = Path.Combine(toDir, dirName);
                CopyDir(fromDirName, toDirName);
            }
        }

        protected void FileManager1_FileUploaded(object sender, UploadFileEventArgs e)
        {
            new BLL.Log().Add(2, "文件管理", string.Format("用户（{0}）上传文件{1}", MySession.CurrentUser.Account, e.UploadedFile.FileManagerPath));
        }

        protected void FileManager1_FileDownload(object sender, DownloadFileCancelEventArgs e)
        {
            new BLL.Log().Add(2, "文件管理", string.Format("用户（{0}）下载文件{1}", MySession.CurrentUser.Account, e.DownloadFile.FileManagerPath));
        }

        protected void FileManager1_ItemRenamed(object sender, RenameEventArgs e)
        {
            new BLL.Log().Add(2, "文件管理", string.Format("用户（{0}）文件重命名{1}", MySession.CurrentUser.Account, e.FileManagerItem.FileManagerPath));
        }

        protected void FileManager1_NewDocumentCreated(object sender, NewDocumentEventArgs e)
        {
            new BLL.Log().Add(2, "文件管理", string.Format("用户（{0}）创建文件{1}", MySession.CurrentUser.Account,e.NewDocument.FileManagerPath));
        }

        protected void FileManager1_NewFolderCreated(object sender, NewFolderEventArgs e)
        {
            new BLL.Log().Add(2, "文件管理", string.Format("用户（{0}）创建文件夹{1}", MySession.CurrentUser.Account,e.NewFolder.FileManagerPath));
        } 
    }
}